package com.huang.rabbitmq.work.lunxun;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/*
*   简单模式
*
* */
public class Consumer2 {

    public static void main(String[] args) {
        //1 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.10");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");

        Connection connection=null;
        Channel channel =null;
        //2  创建连接 connection
        try {
             connection=connectionFactory.newConnection("生产者");
            //3通过连接通道 获取 Channel
             channel = connection.createChannel();
            //4 通过创建的交换机  声明队列 绑定关系  路由key 发送消息和接收消息
            Channel channel1=channel;


            channel1.basicConsume("queue1",true, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery message) throws IOException {

                    try {
                        System.out.println("c1接收到消息，消息是"+new String(message.getBody(),"UTF-8"));
                        Thread.sleep(1000);

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                },new CancelCallback(){
                public void handle(String consumeTag) throws IOException {
                    System.out.println("接受消息失败");
                }
            });


            System.out.println("开始接受消息");
            System.in.read();


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7关闭通道
            //8关闭连接
            if(channel!=null && connection!=null){
                try {
                    channel.close();
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (TimeoutException e) {
                    e.printStackTrace();
                }

            }

        }

    }
}
